home *** CD-ROM | disk | FTP | other *** search
/ Enter 2006 September / Enter 09 2006.iso / Internet / SpamExperts Home 1.1 / SpamExperts Home.exe / lib / spamexperts.modules / logging / __init__.pyc (.txt)
Encoding:
Python Compiled Bytecode  |  2006-07-14  |  42.6 KB  |  1,402 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.4)
  3.  
  4. """
  5. Logging package for Python. Based on PEP 282 and comments thereto in
  6. comp.lang.python, and influenced by Apache's log4j system.
  7.  
  8. Should work under Python versions >= 1.5.2, except that source line
  9. information is not available unless 'sys._getframe()' is.
  10.  
  11. Copyright (C) 2001-2004 Vinay Sajip. All Rights Reserved.
  12.  
  13. To use, simply 'import logging' and log away!
  14. """
  15. import sys
  16. import os
  17. import types
  18. import time
  19. import string
  20. import cStringIO
  21. import traceback
  22.  
  23. try:
  24.     import codecs
  25. except ImportError:
  26.     codecs = None
  27.  
  28.  
  29. try:
  30.     import thread
  31.     import threading
  32. except ImportError:
  33.     thread = None
  34.  
  35. __author__ = 'Vinay Sajip <vinay_sajip@red-dove.com>'
  36. __status__ = 'beta'
  37. __version__ = '0.4.9.7'
  38. __date__ = '07 October 2005'
  39. if hasattr(sys, 'frozen'):
  40.     _srcfile = 'logging%s__init__%s' % (os.sep, __file__[-4:])
  41. elif string.lower(__file__[-4:]) in [
  42.     '.pyc',
  43.     '.pyo']:
  44.     _srcfile = __file__[:-4] + '.py'
  45. else:
  46.     _srcfile = __file__
  47. _srcfile = os.path.normcase(_srcfile)
  48.  
  49. def currentframe():
  50.     """Return the frame object for the caller's stack frame."""
  51.     
  52.     try:
  53.         raise Exception
  54.     except:
  55.         return sys.exc_traceback.tb_frame.f_back
  56.  
  57.  
  58. if hasattr(sys, '_getframe'):
  59.     currentframe = sys._getframe
  60.  
  61. _startTime = time.time()
  62. raiseExceptions = 1
  63. CRITICAL = 50
  64. FATAL = CRITICAL
  65. ERROR = 40
  66. WARNING = 30
  67. WARN = WARNING
  68. INFO = 20
  69. DEBUG = 10
  70. NOTSET = 0
  71. _levelNames = {
  72.     CRITICAL: 'CRITICAL',
  73.     ERROR: 'ERROR',
  74.     WARNING: 'WARNING',
  75.     INFO: 'INFO',
  76.     DEBUG: 'DEBUG',
  77.     NOTSET: 'NOTSET',
  78.     'CRITICAL': CRITICAL,
  79.     'ERROR': ERROR,
  80.     'WARN': WARNING,
  81.     'WARNING': WARNING,
  82.     'INFO': INFO,
  83.     'DEBUG': DEBUG,
  84.     'NOTSET': NOTSET }
  85.  
  86. def getLevelName(level):
  87.     '''
  88.     Return the textual representation of logging level \'level\'.
  89.  
  90.     If the level is one of the predefined levels (CRITICAL, ERROR, WARNING,
  91.     INFO, DEBUG) then you get the corresponding string. If you have
  92.     associated levels with names using addLevelName then the name you have
  93.     associated with \'level\' is returned.
  94.  
  95.     If a numeric value corresponding to one of the defined levels is passed
  96.     in, the corresponding string representation is returned.
  97.  
  98.     Otherwise, the string "Level %s" % level is returned.
  99.     '''
  100.     return _levelNames.get(level, 'Level %s' % level)
  101.  
  102.  
  103. def addLevelName(level, levelName):
  104.     """
  105.     Associate 'levelName' with 'level'.
  106.  
  107.     This is used when converting levels to text during message formatting.
  108.     """
  109.     _acquireLock()
  110.     
  111.     try:
  112.         _levelNames[level] = levelName
  113.         _levelNames[levelName] = level
  114.     finally:
  115.         _releaseLock()
  116.  
  117.  
  118. _lock = None
  119.  
  120. def _acquireLock():
  121.     '''
  122.     Acquire the module-level lock for serializing access to shared data.
  123.  
  124.     This should be released with _releaseLock().
  125.     '''
  126.     global _lock
  127.     if not _lock and thread:
  128.         _lock = threading.RLock()
  129.     
  130.     if _lock:
  131.         _lock.acquire()
  132.     
  133.  
  134.  
  135. def _releaseLock():
  136.     '''
  137.     Release the module-level lock acquired by calling _acquireLock().
  138.     '''
  139.     if _lock:
  140.         _lock.release()
  141.     
  142.  
  143.  
  144. class LogRecord:
  145.     '''
  146.     A LogRecord instance represents an event being logged.
  147.  
  148.     LogRecord instances are created every time something is logged. They
  149.     contain all the information pertinent to the event being logged. The
  150.     main information passed in is in msg and args, which are combined
  151.     using str(msg) % args to create the message field of the record. The
  152.     record also includes information such as when the record was created,
  153.     the source line where the logging call was made, and any exception
  154.     information to be logged.
  155.     '''
  156.     
  157.     def __init__(self, name, level, pathname, lineno, msg, args, exc_info):
  158.         '''
  159.         Initialize a logging record with interesting information.
  160.         '''
  161.         ct = time.time()
  162.         self.name = name
  163.         self.msg = msg
  164.         if args and len(args) == 1 and args[0] and type(args[0]) == types.DictType:
  165.             args = args[0]
  166.         
  167.         self.args = args
  168.         self.levelname = getLevelName(level)
  169.         self.levelno = level
  170.         self.pathname = pathname
  171.         
  172.         try:
  173.             self.filename = os.path.basename(pathname)
  174.             self.module = os.path.splitext(self.filename)[0]
  175.         except:
  176.             self.filename = pathname
  177.             self.module = 'Unknown module'
  178.  
  179.         self.exc_info = exc_info
  180.         self.exc_text = None
  181.         self.lineno = lineno
  182.         self.created = ct
  183.         self.msecs = (ct - long(ct)) * 1000
  184.         self.relativeCreated = (self.created - _startTime) * 1000
  185.         if thread:
  186.             self.thread = thread.get_ident()
  187.             self.threadName = threading.currentThread().getName()
  188.         else:
  189.             self.thread = None
  190.             self.threadName = None
  191.         if hasattr(os, 'getpid'):
  192.             self.process = os.getpid()
  193.         else:
  194.             self.process = None
  195.  
  196.     
  197.     def __str__(self):
  198.         return '<LogRecord: %s, %s, %s, %s, "%s">' % (self.name, self.levelno, self.pathname, self.lineno, self.msg)
  199.  
  200.     
  201.     def getMessage(self):
  202.         '''
  203.         Return the message for this LogRecord.
  204.  
  205.         Return the message for this LogRecord after merging any user-supplied
  206.         arguments with the message.
  207.         '''
  208.         if not hasattr(types, 'UnicodeType'):
  209.             msg = str(self.msg)
  210.         else:
  211.             msg = self.msg
  212.             if type(msg) not in (types.UnicodeType, types.StringType):
  213.                 
  214.                 try:
  215.                     msg = str(self.msg)
  216.                 except UnicodeError:
  217.                     msg = self.msg
  218.                 except:
  219.                     None<EXCEPTION MATCH>UnicodeError
  220.                 
  221.  
  222.             None<EXCEPTION MATCH>UnicodeError
  223.         if self.args:
  224.             msg = msg % self.args
  225.         
  226.         return msg
  227.  
  228.  
  229.  
  230. def makeLogRecord(dict):
  231.     '''
  232.     Make a LogRecord whose attributes are defined by the specified dictionary,
  233.     This function is useful for converting a logging event received over
  234.     a socket connection (which is sent as a dictionary) into a LogRecord
  235.     instance.
  236.     '''
  237.     rv = LogRecord(None, None, '', 0, '', (), None)
  238.     rv.__dict__.update(dict)
  239.     return rv
  240.  
  241.  
  242. class Formatter:
  243.     '''
  244.     Formatter instances are used to convert a LogRecord to text.
  245.  
  246.     Formatters need to know how a LogRecord is constructed. They are
  247.     responsible for converting a LogRecord to (usually) a string which can
  248.     be interpreted by either a human or an external system. The base Formatter
  249.     allows a formatting string to be specified. If none is supplied, the
  250.     default value of "%s(message)\\n" is used.
  251.  
  252.     The Formatter can be initialized with a format string which makes use of
  253.     knowledge of the LogRecord attributes - e.g. the default value mentioned
  254.     above makes use of the fact that the user\'s message and arguments are pre-
  255.     formatted into a LogRecord\'s message attribute. Currently, the useful
  256.     attributes in a LogRecord are described by:
  257.  
  258.     %(name)s            Name of the logger (logging channel)
  259.     %(levelno)s         Numeric logging level for the message (DEBUG, INFO,
  260.                         WARNING, ERROR, CRITICAL)
  261.     %(levelname)s       Text logging level for the message ("DEBUG", "INFO",
  262.                         "WARNING", "ERROR", "CRITICAL")
  263.     %(pathname)s        Full pathname of the source file where the logging
  264.                         call was issued (if available)
  265.     %(filename)s        Filename portion of pathname
  266.     %(module)s          Module (name portion of filename)
  267.     %(lineno)d          Source line number where the logging call was issued
  268.                         (if available)
  269.     %(created)f         Time when the LogRecord was created (time.time()
  270.                         return value)
  271.     %(asctime)s         Textual time when the LogRecord was created
  272.     %(msecs)d           Millisecond portion of the creation time
  273.     %(relativeCreated)d Time in milliseconds when the LogRecord was created,
  274.                         relative to the time the logging module was loaded
  275.                         (typically at application startup time)
  276.     %(thread)d          Thread ID (if available)
  277.     %(threadName)s      Thread name (if available)
  278.     %(process)d         Process ID (if available)
  279.     %(message)s         The result of record.getMessage(), computed just as
  280.                         the record is emitted
  281.     '''
  282.     converter = time.localtime
  283.     
  284.     def __init__(self, fmt = None, datefmt = None):
  285.         '''
  286.         Initialize the formatter with specified format strings.
  287.  
  288.         Initialize the formatter either with the specified format string, or a
  289.         default as described above. Allow for specialized date formatting with
  290.         the optional datefmt argument (if omitted, you get the ISO8601 format).
  291.         '''
  292.         if fmt:
  293.             self._fmt = fmt
  294.         else:
  295.             self._fmt = '%(message)s'
  296.         self.datefmt = datefmt
  297.  
  298.     
  299.     def formatTime(self, record, datefmt = None):
  300.         """
  301.         Return the creation time of the specified LogRecord as formatted text.
  302.  
  303.         This method should be called from format() by a formatter which
  304.         wants to make use of a formatted time. This method can be overridden
  305.         in formatters to provide for any specific requirement, but the
  306.         basic behaviour is as follows: if datefmt (a string) is specified,
  307.         it is used with time.strftime() to format the creation time of the
  308.         record. Otherwise, the ISO8601 format is used. The resulting
  309.         string is returned. This function uses a user-configurable function
  310.         to convert the creation time to a tuple. By default, time.localtime()
  311.         is used; to change this for a particular formatter instance, set the
  312.         'converter' attribute to a function with the same signature as
  313.         time.localtime() or time.gmtime(). To change it for all formatters,
  314.         for example if you want all logging times to be shown in GMT,
  315.         set the 'converter' attribute in the Formatter class.
  316.         """
  317.         ct = self.converter(record.created)
  318.         if datefmt:
  319.             s = time.strftime(datefmt, ct)
  320.         else:
  321.             t = time.strftime('%Y-%m-%d %H:%M:%S', ct)
  322.             s = '%s,%03d' % (t, record.msecs)
  323.         return s
  324.  
  325.     
  326.     def formatException(self, ei):
  327.         '''
  328.         Format and return the specified exception information as a string.
  329.  
  330.         This default implementation just uses
  331.         traceback.print_exception()
  332.         '''
  333.         sio = cStringIO.StringIO()
  334.         traceback.print_exception(ei[0], ei[1], ei[2], None, sio)
  335.         s = sio.getvalue()
  336.         sio.close()
  337.         if s[-1] == '\n':
  338.             s = s[:-1]
  339.         
  340.         return s
  341.  
  342.     
  343.     def format(self, record):
  344.         '''
  345.         Format the specified record as text.
  346.  
  347.         The record\'s attribute dictionary is used as the operand to a
  348.         string formatting operation which yields the returned string.
  349.         Before formatting the dictionary, a couple of preparatory steps
  350.         are carried out. The message attribute of the record is computed
  351.         using LogRecord.getMessage(). If the formatting string contains
  352.         "%(asctime)", formatTime() is called to format the event time.
  353.         If there is exception information, it is formatted using
  354.         formatException() and appended to the message.
  355.         '''
  356.         record.message = record.getMessage()
  357.         if string.find(self._fmt, '%(asctime)') >= 0:
  358.             record.asctime = self.formatTime(record, self.datefmt)
  359.         
  360.         s = self._fmt % record.__dict__
  361.         if record.exc_info:
  362.             if not record.exc_text:
  363.                 record.exc_text = self.formatException(record.exc_info)
  364.             
  365.         
  366.         if record.exc_text:
  367.             if s[-1] != '\n':
  368.                 s = s + '\n'
  369.             
  370.             s = s + record.exc_text
  371.         
  372.         return s
  373.  
  374.  
  375. _defaultFormatter = Formatter()
  376.  
  377. class BufferingFormatter:
  378.     '''
  379.     A formatter suitable for formatting a number of records.
  380.     '''
  381.     
  382.     def __init__(self, linefmt = None):
  383.         '''
  384.         Optionally specify a formatter which will be used to format each
  385.         individual record.
  386.         '''
  387.         if linefmt:
  388.             self.linefmt = linefmt
  389.         else:
  390.             self.linefmt = _defaultFormatter
  391.  
  392.     
  393.     def formatHeader(self, records):
  394.         '''
  395.         Return the header string for the specified records.
  396.         '''
  397.         return ''
  398.  
  399.     
  400.     def formatFooter(self, records):
  401.         '''
  402.         Return the footer string for the specified records.
  403.         '''
  404.         return ''
  405.  
  406.     
  407.     def format(self, records):
  408.         '''
  409.         Format the specified records and return the result as a string.
  410.         '''
  411.         rv = ''
  412.         if len(records) > 0:
  413.             rv = rv + self.formatHeader(records)
  414.             for record in records:
  415.                 rv = rv + self.linefmt.format(record)
  416.             
  417.             rv = rv + self.formatFooter(records)
  418.         
  419.         return rv
  420.  
  421.  
  422.  
  423. class Filter:
  424.     '''
  425.     Filter instances are used to perform arbitrary filtering of LogRecords.
  426.  
  427.     Loggers and Handlers can optionally use Filter instances to filter
  428.     records as desired. The base filter class only allows events which are
  429.     below a certain point in the logger hierarchy. For example, a filter
  430.     initialized with "A.B" will allow events logged by loggers "A.B",
  431.     "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
  432.     initialized with the empty string, all events are passed.
  433.     '''
  434.     
  435.     def __init__(self, name = ''):
  436.         '''
  437.         Initialize a filter.
  438.  
  439.         Initialize with the name of the logger which, together with its
  440.         children, will have its events allowed through the filter. If no
  441.         name is specified, allow every event.
  442.         '''
  443.         self.name = name
  444.         self.nlen = len(name)
  445.  
  446.     
  447.     def filter(self, record):
  448.         '''
  449.         Determine if the specified record is to be logged.
  450.  
  451.         Is the specified record to be logged? Returns 0 for no, nonzero for
  452.         yes. If deemed appropriate, the record may be modified in-place.
  453.         '''
  454.         if self.nlen == 0:
  455.             return 1
  456.         elif self.name == record.name:
  457.             return 1
  458.         elif string.find(record.name, self.name, 0, self.nlen) != 0:
  459.             return 0
  460.         
  461.         return record.name[self.nlen] == '.'
  462.  
  463.  
  464.  
  465. class Filterer:
  466.     '''
  467.     A base class for loggers and handlers which allows them to share
  468.     common code.
  469.     '''
  470.     
  471.     def __init__(self):
  472.         '''
  473.         Initialize the list of filters to be an empty list.
  474.         '''
  475.         self.filters = []
  476.  
  477.     
  478.     def addFilter(self, filter):
  479.         '''
  480.         Add the specified filter to this handler.
  481.         '''
  482.         if filter not in self.filters:
  483.             self.filters.append(filter)
  484.         
  485.  
  486.     
  487.     def removeFilter(self, filter):
  488.         '''
  489.         Remove the specified filter from this handler.
  490.         '''
  491.         if filter in self.filters:
  492.             self.filters.remove(filter)
  493.         
  494.  
  495.     
  496.     def filter(self, record):
  497.         '''
  498.         Determine if a record is loggable by consulting all the filters.
  499.  
  500.         The default is to allow the record to be logged; any filter can veto
  501.         this and the record is then dropped. Returns a zero value if a record
  502.         is to be dropped, else non-zero.
  503.         '''
  504.         rv = 1
  505.         for f in self.filters:
  506.             if not f.filter(record):
  507.                 rv = 0
  508.                 break
  509.                 continue
  510.         
  511.         return rv
  512.  
  513.  
  514. _handlers = { }
  515. _handlerList = []
  516.  
  517. class Handler(Filterer):
  518.     """
  519.     Handler instances dispatch logging events to specific destinations.
  520.  
  521.     The base handler class. Acts as a placeholder which defines the Handler
  522.     interface. Handlers can optionally use Formatter instances to format
  523.     records as desired. By default, no formatter is specified; in this case,
  524.     the 'raw' message as determined by record.message is logged.
  525.     """
  526.     
  527.     def __init__(self, level = NOTSET):
  528.         '''
  529.         Initializes the instance - basically setting the formatter to None
  530.         and the filter list to empty.
  531.         '''
  532.         Filterer.__init__(self)
  533.         self.level = level
  534.         self.formatter = None
  535.         _acquireLock()
  536.         
  537.         try:
  538.             _handlers[self] = 1
  539.             _handlerList.insert(0, self)
  540.         finally:
  541.             _releaseLock()
  542.  
  543.         self.createLock()
  544.  
  545.     
  546.     def createLock(self):
  547.         '''
  548.         Acquire a thread lock for serializing access to the underlying I/O.
  549.         '''
  550.         if thread:
  551.             self.lock = threading.RLock()
  552.         else:
  553.             self.lock = None
  554.  
  555.     
  556.     def acquire(self):
  557.         '''
  558.         Acquire the I/O thread lock.
  559.         '''
  560.         if self.lock:
  561.             self.lock.acquire()
  562.         
  563.  
  564.     
  565.     def release(self):
  566.         '''
  567.         Release the I/O thread lock.
  568.         '''
  569.         if self.lock:
  570.             self.lock.release()
  571.         
  572.  
  573.     
  574.     def setLevel(self, level):
  575.         '''
  576.         Set the logging level of this handler.
  577.         '''
  578.         self.level = level
  579.  
  580.     
  581.     def format(self, record):
  582.         '''
  583.         Format the specified record.
  584.  
  585.         If a formatter is set, use it. Otherwise, use the default formatter
  586.         for the module.
  587.         '''
  588.         if self.formatter:
  589.             fmt = self.formatter
  590.         else:
  591.             fmt = _defaultFormatter
  592.         return fmt.format(record)
  593.  
  594.     
  595.     def emit(self, record):
  596.         '''
  597.         Do whatever it takes to actually log the specified logging record.
  598.  
  599.         This version is intended to be implemented by subclasses and so
  600.         raises a NotImplementedError.
  601.         '''
  602.         raise NotImplementedError, 'emit must be implemented by Handler subclasses'
  603.  
  604.     
  605.     def handle(self, record):
  606.         '''
  607.         Conditionally emit the specified logging record.
  608.  
  609.         Emission depends on filters which may have been added to the handler.
  610.         Wrap the actual emission of the record with acquisition/release of
  611.         the I/O thread lock. Returns whether the filter passed the record for
  612.         emission.
  613.         '''
  614.         rv = self.filter(record)
  615.         if rv:
  616.             self.acquire()
  617.             
  618.             try:
  619.                 self.emit(record)
  620.             finally:
  621.                 self.release()
  622.  
  623.         
  624.         return rv
  625.  
  626.     
  627.     def setFormatter(self, fmt):
  628.         '''
  629.         Set the formatter for this handler.
  630.         '''
  631.         self.formatter = fmt
  632.  
  633.     
  634.     def flush(self):
  635.         '''
  636.         Ensure all logging output has been flushed.
  637.  
  638.         This version does nothing and is intended to be implemented by
  639.         subclasses.
  640.         '''
  641.         pass
  642.  
  643.     
  644.     def close(self):
  645.         '''
  646.         Tidy up any resources used by the handler.
  647.  
  648.         This version does removes the handler from an internal list
  649.         of handlers which is closed when shutdown() is called. Subclasses
  650.         should ensure that this gets called from overridden close()
  651.         methods.
  652.         '''
  653.         _acquireLock()
  654.         
  655.         try:
  656.             del _handlers[self]
  657.             _handlerList.remove(self)
  658.         finally:
  659.             _releaseLock()
  660.  
  661.  
  662.     
  663.     def handleError(self, record):
  664.         '''
  665.         Handle errors which occur during an emit() call.
  666.  
  667.         This method should be called from handlers when an exception is
  668.         encountered during an emit() call. If raiseExceptions is false,
  669.         exceptions get silently ignored. This is what is mostly wanted
  670.         for a logging system - most users will not care about errors in
  671.         the logging system, they are more interested in application errors.
  672.         You could, however, replace this with a custom handler if you wish.
  673.         The record which was being processed is passed in to this method.
  674.         '''
  675.         if raiseExceptions:
  676.             ei = sys.exc_info()
  677.             traceback.print_exception(ei[0], ei[1], ei[2], None, sys.stderr)
  678.             del ei
  679.         
  680.  
  681.  
  682.  
  683. class StreamHandler(Handler):
  684.     '''
  685.     A handler class which writes logging records, appropriately formatted,
  686.     to a stream. Note that this class does not close the stream, as
  687.     sys.stdout or sys.stderr may be used.
  688.     '''
  689.     
  690.     def __init__(self, strm = None):
  691.         '''
  692.         Initialize the handler.
  693.  
  694.         If strm is not specified, sys.stderr is used.
  695.         '''
  696.         Handler.__init__(self)
  697.         if not strm:
  698.             strm = sys.stderr
  699.         
  700.         self.stream = strm
  701.         self.formatter = None
  702.  
  703.     
  704.     def flush(self):
  705.         '''
  706.         Flushes the stream.
  707.         '''
  708.         self.stream.flush()
  709.  
  710.     
  711.     def emit(self, record):
  712.         '''
  713.         Emit a record.
  714.  
  715.         If a formatter is specified, it is used to format the record.
  716.         The record is then written to the stream with a trailing newline
  717.         [N.B. this may be removed depending on feedback]. If exception
  718.         information is present, it is formatted using
  719.         traceback.print_exception and appended to the stream.
  720.         '''
  721.         
  722.         try:
  723.             msg = self.format(record)
  724.             fs = '%s\n'
  725.             if not hasattr(types, 'UnicodeType'):
  726.                 self.stream.write(fs % msg)
  727.             else:
  728.                 
  729.                 try:
  730.                     self.stream.write(fs % msg)
  731.                 except UnicodeError:
  732.                     self.stream.write(fs % msg.encode('UTF-8'))
  733.  
  734.             self.flush()
  735.         except (KeyboardInterrupt, SystemExit):
  736.             raise 
  737.         except:
  738.             self.handleError(record)
  739.  
  740.  
  741.  
  742.  
  743. class FileHandler(StreamHandler):
  744.     '''
  745.     A handler class which writes formatted logging records to disk files.
  746.     '''
  747.     
  748.     def __init__(self, filename, mode = 'a', encoding = None):
  749.         '''
  750.         Open the specified file and use it as the stream for logging.
  751.         '''
  752.         if codecs is None:
  753.             encoding = None
  754.         
  755.         if encoding is None:
  756.             stream = open(filename, mode)
  757.         else:
  758.             stream = codecs.open(filename, mode, encoding)
  759.         StreamHandler.__init__(self, stream)
  760.         self.baseFilename = os.path.abspath(filename)
  761.         self.mode = mode
  762.  
  763.     
  764.     def close(self):
  765.         '''
  766.         Closes the stream.
  767.         '''
  768.         self.flush()
  769.         self.stream.close()
  770.         StreamHandler.close(self)
  771.  
  772.  
  773.  
  774. class PlaceHolder:
  775.     '''
  776.     PlaceHolder instances are used in the Manager logger hierarchy to take
  777.     the place of nodes for which no loggers have been defined. This class is
  778.     intended for internal use only and not as part of the public API.
  779.     '''
  780.     
  781.     def __init__(self, alogger):
  782.         '''
  783.         Initialize with the specified logger being a child of this placeholder.
  784.         '''
  785.         self.loggerMap = {
  786.             alogger: None }
  787.  
  788.     
  789.     def append(self, alogger):
  790.         '''
  791.         Add the specified logger as a child of this placeholder.
  792.         '''
  793.         if not self.loggerMap.has_key(alogger):
  794.             self.loggerMap[alogger] = None
  795.         
  796.  
  797.  
  798. _loggerClass = None
  799.  
  800. def setLoggerClass(klass):
  801.     '''
  802.     Set the class to be used when instantiating a logger. The class should
  803.     define __init__() such that only a name argument is required, and the
  804.     __init__() should call Logger.__init__()
  805.     '''
  806.     global _loggerClass
  807.     if klass != Logger:
  808.         if not issubclass(klass, Logger):
  809.             raise TypeError, 'logger not derived from logging.Logger: ' + klass.__name__
  810.         
  811.     
  812.     _loggerClass = klass
  813.  
  814.  
  815. def getLoggerClass():
  816.     '''
  817.     Return the class to be used when instantiating a logger.
  818.     '''
  819.     return _loggerClass
  820.  
  821.  
  822. class Manager:
  823.     '''
  824.     There is [under normal circumstances] just one Manager instance, which
  825.     holds the hierarchy of loggers.
  826.     '''
  827.     
  828.     def __init__(self, rootnode):
  829.         '''
  830.         Initialize the manager with the root node of the logger hierarchy.
  831.         '''
  832.         self.root = rootnode
  833.         self.disable = 0
  834.         self.emittedNoHandlerWarning = 0
  835.         self.loggerDict = { }
  836.  
  837.     
  838.     def getLogger(self, name):
  839.         '''
  840.         Get a logger with the specified name (channel name), creating it
  841.         if it doesn\'t yet exist. This name is a dot-separated hierarchical
  842.         name, such as "a", "a.b", "a.b.c" or similar.
  843.  
  844.         If a PlaceHolder existed for the specified name [i.e. the logger
  845.         didn\'t exist but a child of it did], replace it with the created
  846.         logger and fix up the parent/child references which pointed to the
  847.         placeholder to now point to the logger.
  848.         '''
  849.         rv = None
  850.         _acquireLock()
  851.         
  852.         try:
  853.             if self.loggerDict.has_key(name):
  854.                 rv = self.loggerDict[name]
  855.                 if isinstance(rv, PlaceHolder):
  856.                     ph = rv
  857.                     rv = _loggerClass(name)
  858.                     rv.manager = self
  859.                     self.loggerDict[name] = rv
  860.                     self._fixupChildren(ph, rv)
  861.                     self._fixupParents(rv)
  862.                 
  863.             else:
  864.                 rv = _loggerClass(name)
  865.                 rv.manager = self
  866.                 self.loggerDict[name] = rv
  867.                 self._fixupParents(rv)
  868.         finally:
  869.             _releaseLock()
  870.  
  871.         return rv
  872.  
  873.     
  874.     def _fixupParents(self, alogger):
  875.         '''
  876.         Ensure that there are either loggers or placeholders all the way
  877.         from the specified logger to the root of the logger hierarchy.
  878.         '''
  879.         name = alogger.name
  880.         i = string.rfind(name, '.')
  881.         rv = None
  882.         while i > 0 and not rv:
  883.             substr = name[:i]
  884.             if not self.loggerDict.has_key(substr):
  885.                 self.loggerDict[substr] = PlaceHolder(alogger)
  886.             else:
  887.                 obj = self.loggerDict[substr]
  888.                 if isinstance(obj, Logger):
  889.                     rv = obj
  890.                 elif not isinstance(obj, PlaceHolder):
  891.                     raise AssertionError
  892.                 obj.append(alogger)
  893.             i = string.rfind(name, '.', 0, i - 1)
  894.         if not rv:
  895.             rv = self.root
  896.         
  897.         alogger.parent = rv
  898.  
  899.     
  900.     def _fixupChildren(self, ph, alogger):
  901.         '''
  902.         Ensure that children of the placeholder ph are connected to the
  903.         specified logger.
  904.         '''
  905.         for c in ph.loggerMap.keys():
  906.             if string.find(c.parent.name, alogger.name) != 0:
  907.                 alogger.parent = c.parent
  908.                 c.parent = alogger
  909.                 continue
  910.         
  911.  
  912.  
  913.  
  914. class Logger(Filterer):
  915.     '''
  916.     Instances of the Logger class represent a single logging channel. A
  917.     "logging channel" indicates an area of an application. Exactly how an
  918.     "area" is defined is up to the application developer. Since an
  919.     application can have any number of areas, logging channels are identified
  920.     by a unique string. Application areas can be nested (e.g. an area
  921.     of "input processing" might include sub-areas "read CSV files", "read
  922.     XLS files" and "read Gnumeric files"). To cater for this natural nesting,
  923.     channel names are organized into a namespace hierarchy where levels are
  924.     separated by periods, much like the Java or Python package namespace. So
  925.     in the instance given above, channel names might be "input" for the upper
  926.     level, and "input.csv", "input.xls" and "input.gnu" for the sub-levels.
  927.     There is no arbitrary limit to the depth of nesting.
  928.     '''
  929.     
  930.     def __init__(self, name, level = NOTSET):
  931.         '''
  932.         Initialize the logger with a name and an optional level.
  933.         '''
  934.         Filterer.__init__(self)
  935.         self.name = name
  936.         self.level = level
  937.         self.parent = None
  938.         self.propagate = 1
  939.         self.handlers = []
  940.         self.disabled = 0
  941.  
  942.     
  943.     def setLevel(self, level):
  944.         '''
  945.         Set the logging level of this logger.
  946.         '''
  947.         self.level = level
  948.  
  949.     
  950.     def debug(self, msg, *args, **kwargs):
  951.         '''
  952.         Log \'msg % args\' with severity \'DEBUG\'.
  953.  
  954.         To pass exception information, use the keyword argument exc_info with
  955.         a true value, e.g.
  956.  
  957.         logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)
  958.         '''
  959.         if self.manager.disable >= DEBUG:
  960.             return None
  961.         
  962.         if DEBUG >= self.getEffectiveLevel():
  963.             apply(self._log, (DEBUG, msg, args), kwargs)
  964.         
  965.  
  966.     
  967.     def info(self, msg, *args, **kwargs):
  968.         '''
  969.         Log \'msg % args\' with severity \'INFO\'.
  970.  
  971.         To pass exception information, use the keyword argument exc_info with
  972.         a true value, e.g.
  973.  
  974.         logger.info("Houston, we have a %s", "interesting problem", exc_info=1)
  975.         '''
  976.         if self.manager.disable >= INFO:
  977.             return None
  978.         
  979.         if INFO >= self.getEffectiveLevel():
  980.             apply(self._log, (INFO, msg, args), kwargs)
  981.         
  982.  
  983.     
  984.     def warning(self, msg, *args, **kwargs):
  985.         '''
  986.         Log \'msg % args\' with severity \'WARNING\'.
  987.  
  988.         To pass exception information, use the keyword argument exc_info with
  989.         a true value, e.g.
  990.  
  991.         logger.warning("Houston, we have a %s", "bit of a problem", exc_info=1)
  992.         '''
  993.         if self.manager.disable >= WARNING:
  994.             return None
  995.         
  996.         if self.isEnabledFor(WARNING):
  997.             apply(self._log, (WARNING, msg, args), kwargs)
  998.         
  999.  
  1000.     warn = warning
  1001.     
  1002.     def error(self, msg, *args, **kwargs):
  1003.         '''
  1004.         Log \'msg % args\' with severity \'ERROR\'.
  1005.  
  1006.         To pass exception information, use the keyword argument exc_info with
  1007.         a true value, e.g.
  1008.  
  1009.         logger.error("Houston, we have a %s", "major problem", exc_info=1)
  1010.         '''
  1011.         if self.manager.disable >= ERROR:
  1012.             return None
  1013.         
  1014.         if self.isEnabledFor(ERROR):
  1015.             apply(self._log, (ERROR, msg, args), kwargs)
  1016.         
  1017.  
  1018.     
  1019.     def exception(self, msg, *args):
  1020.         '''
  1021.         Convenience method for logging an ERROR with exception information.
  1022.         '''
  1023.         apply(self.error, (msg,) + args, {
  1024.             'exc_info': 1 })
  1025.  
  1026.     
  1027.     def critical(self, msg, *args, **kwargs):
  1028.         '''
  1029.         Log \'msg % args\' with severity \'CRITICAL\'.
  1030.  
  1031.         To pass exception information, use the keyword argument exc_info with
  1032.         a true value, e.g.
  1033.  
  1034.         logger.critical("Houston, we have a %s", "major disaster", exc_info=1)
  1035.         '''
  1036.         if self.manager.disable >= CRITICAL:
  1037.             return None
  1038.         
  1039.         if CRITICAL >= self.getEffectiveLevel():
  1040.             apply(self._log, (CRITICAL, msg, args), kwargs)
  1041.         
  1042.  
  1043.     fatal = critical
  1044.     
  1045.     def log(self, level, msg, *args, **kwargs):
  1046.         '''
  1047.         Log \'msg % args\' with the integer severity \'level\'.
  1048.  
  1049.         To pass exception information, use the keyword argument exc_info with
  1050.         a true value, e.g.
  1051.  
  1052.         logger.log(level, "We have a %s", "mysterious problem", exc_info=1)
  1053.         '''
  1054.         if type(level) != types.IntType:
  1055.             if raiseExceptions:
  1056.                 raise TypeError, 'level must be an integer'
  1057.             else:
  1058.                 return None
  1059.         
  1060.         if self.manager.disable >= level:
  1061.             return None
  1062.         
  1063.         if self.isEnabledFor(level):
  1064.             apply(self._log, (level, msg, args), kwargs)
  1065.         
  1066.  
  1067.     
  1068.     def findCaller(self):
  1069.         '''
  1070.         Find the stack frame of the caller so that we can note the source
  1071.         file name, line number and function name.
  1072.         '''
  1073.         f = currentframe().f_back
  1074.         rv = ('(unknown file)', 0, '(unknown function)')
  1075.         while hasattr(f, 'f_code'):
  1076.             co = f.f_code
  1077.             filename = os.path.normcase(co.co_filename)
  1078.             if filename == _srcfile:
  1079.                 f = f.f_back
  1080.                 continue
  1081.             
  1082.             rv = (filename, f.f_lineno, co.co_name)
  1083.             break
  1084.         return rv
  1085.  
  1086.     
  1087.     def makeRecord(self, name, level, fn, lno, msg, args, exc_info):
  1088.         '''
  1089.         A factory method which can be overridden in subclasses to create
  1090.         specialized LogRecords.
  1091.         '''
  1092.         return LogRecord(name, level, fn, lno, msg, args, exc_info)
  1093.  
  1094.     
  1095.     def _log(self, level, msg, args, exc_info = None):
  1096.         '''
  1097.         Low-level logging routine which creates a LogRecord and then calls
  1098.         all the handlers of this logger to handle the record.
  1099.         '''
  1100.         if _srcfile:
  1101.             (fn, lno, func) = self.findCaller()
  1102.         else:
  1103.             (fn, lno, func) = ('(unknown file)', 0, '(unknown function)')
  1104.         if exc_info:
  1105.             if type(exc_info) != types.TupleType:
  1106.                 exc_info = sys.exc_info()
  1107.             
  1108.         
  1109.         record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info)
  1110.         self.handle(record)
  1111.  
  1112.     
  1113.     def handle(self, record):
  1114.         '''
  1115.         Call the handlers for the specified record.
  1116.  
  1117.         This method is used for unpickled records received from a socket, as
  1118.         well as those created locally. Logger-level filtering is applied.
  1119.         '''
  1120.         if not (self.disabled) and self.filter(record):
  1121.             self.callHandlers(record)
  1122.         
  1123.  
  1124.     
  1125.     def addHandler(self, hdlr):
  1126.         '''
  1127.         Add the specified handler to this logger.
  1128.         '''
  1129.         if hdlr not in self.handlers:
  1130.             self.handlers.append(hdlr)
  1131.         
  1132.  
  1133.     
  1134.     def removeHandler(self, hdlr):
  1135.         '''
  1136.         Remove the specified handler from this logger.
  1137.         '''
  1138.         if hdlr in self.handlers:
  1139.             hdlr.acquire()
  1140.             
  1141.             try:
  1142.                 self.handlers.remove(hdlr)
  1143.             finally:
  1144.                 hdlr.release()
  1145.  
  1146.         
  1147.  
  1148.     
  1149.     def callHandlers(self, record):
  1150.         '''
  1151.         Pass a record to all relevant handlers.
  1152.  
  1153.         Loop through all handlers for this logger and its parents in the
  1154.         logger hierarchy. If no handler was found, output a one-off error
  1155.         message to sys.stderr. Stop searching up the hierarchy whenever a
  1156.         logger with the "propagate" attribute set to zero is found - that
  1157.         will be the last logger whose handlers are called.
  1158.         '''
  1159.         c = self
  1160.         found = 0
  1161.         while c:
  1162.             for hdlr in c.handlers:
  1163.                 found = found + 1
  1164.                 if record.levelno >= hdlr.level:
  1165.                     hdlr.handle(record)
  1166.                     continue
  1167.             
  1168.             if not c.propagate:
  1169.                 c = None
  1170.                 continue
  1171.             c = c.parent
  1172.         if found == 0 and raiseExceptions and not (self.manager.emittedNoHandlerWarning):
  1173.             sys.stderr.write('No handlers could be found for logger "%s"\n' % self.name)
  1174.             self.manager.emittedNoHandlerWarning = 1
  1175.         
  1176.  
  1177.     
  1178.     def getEffectiveLevel(self):
  1179.         '''
  1180.         Get the effective level for this logger.
  1181.  
  1182.         Loop through this logger and its parents in the logger hierarchy,
  1183.         looking for a non-zero logging level. Return the first one found.
  1184.         '''
  1185.         logger = self
  1186.         while logger:
  1187.             if logger.level:
  1188.                 return logger.level
  1189.             
  1190.             logger = logger.parent
  1191.         return NOTSET
  1192.  
  1193.     
  1194.     def isEnabledFor(self, level):
  1195.         """
  1196.         Is this logger enabled for level 'level'?
  1197.         """
  1198.         if self.manager.disable >= level:
  1199.             return 0
  1200.         
  1201.         return level >= self.getEffectiveLevel()
  1202.  
  1203.  
  1204.  
  1205. class RootLogger(Logger):
  1206.     '''
  1207.     A root logger is not that different to any other logger, except that
  1208.     it must have a logging level and there is only one instance of it in
  1209.     the hierarchy.
  1210.     '''
  1211.     
  1212.     def __init__(self, level):
  1213.         '''
  1214.         Initialize the logger with the name "root".
  1215.         '''
  1216.         Logger.__init__(self, 'root', level)
  1217.  
  1218.  
  1219. _loggerClass = Logger
  1220. root = RootLogger(WARNING)
  1221. Logger.root = root
  1222. Logger.manager = Manager(Logger.root)
  1223. BASIC_FORMAT = '%(levelname)s:%(name)s:%(message)s'
  1224.  
  1225. def basicConfig(**kwargs):
  1226.     """
  1227.     Do basic configuration for the logging system.
  1228.  
  1229.     This function does nothing if the root logger already has handlers
  1230.     configured. It is a convenience method intended for use by simple scripts
  1231.     to do one-shot configuration of the logging package.
  1232.  
  1233.     The default behaviour is to create a StreamHandler which writes to
  1234.     sys.stderr, set a formatter using the BASIC_FORMAT format string, and
  1235.     add the handler to the root logger.
  1236.  
  1237.     A number of optional keyword arguments may be specified, which can alter
  1238.     the default behaviour.
  1239.  
  1240.     filename  Specifies that a FileHandler be created, using the specified
  1241.               filename, rather than a StreamHandler.
  1242.     filemode  Specifies the mode to open the file, if filename is specified
  1243.               (if filemode is unspecified, it defaults to 'a').
  1244.     format    Use the specified format string for the handler.
  1245.     datefmt   Use the specified date/time format.
  1246.     level     Set the root logger level to the specified level.
  1247.     stream    Use the specified stream to initialize the StreamHandler. Note
  1248.               that this argument is incompatible with 'filename' - if both
  1249.               are present, 'stream' is ignored.
  1250.  
  1251.     Note that you could specify a stream created using open(filename, mode)
  1252.     rather than passing the filename and mode in. However, it should be
  1253.     remembered that StreamHandler does not close its stream (since it may be
  1254.     using sys.stdout or sys.stderr), whereas FileHandler closes its stream
  1255.     when the handler is closed.
  1256.     """
  1257.     if len(root.handlers) == 0:
  1258.         filename = kwargs.get('filename')
  1259.         if filename:
  1260.             mode = kwargs.get('filemode', 'a')
  1261.             hdlr = FileHandler(filename, mode)
  1262.         else:
  1263.             stream = kwargs.get('stream')
  1264.             hdlr = StreamHandler(stream)
  1265.         fs = kwargs.get('format', BASIC_FORMAT)
  1266.         dfs = kwargs.get('datefmt', None)
  1267.         fmt = Formatter(fs, dfs)
  1268.         hdlr.setFormatter(fmt)
  1269.         root.addHandler(hdlr)
  1270.         level = kwargs.get('level')
  1271.         if level:
  1272.             root.setLevel(level)
  1273.         
  1274.     
  1275.  
  1276.  
  1277. def getLogger(name = None):
  1278.     '''
  1279.     Return a logger with the specified name, creating it if necessary.
  1280.  
  1281.     If no name is specified, return the root logger.
  1282.     '''
  1283.     if name:
  1284.         return Logger.manager.getLogger(name)
  1285.     else:
  1286.         return root
  1287.  
  1288.  
  1289. def critical(msg, *args, **kwargs):
  1290.     """
  1291.     Log a message with severity 'CRITICAL' on the root logger.
  1292.     """
  1293.     if len(root.handlers) == 0:
  1294.         basicConfig()
  1295.     
  1296.     apply(root.critical, (msg,) + args, kwargs)
  1297.  
  1298. fatal = critical
  1299.  
  1300. def error(msg, *args, **kwargs):
  1301.     """
  1302.     Log a message with severity 'ERROR' on the root logger.
  1303.     """
  1304.     if len(root.handlers) == 0:
  1305.         basicConfig()
  1306.     
  1307.     apply(root.error, (msg,) + args, kwargs)
  1308.  
  1309.  
  1310. def exception(msg, *args):
  1311.     """
  1312.     Log a message with severity 'ERROR' on the root logger,
  1313.     with exception information.
  1314.     """
  1315.     apply(error, (msg,) + args, {
  1316.         'exc_info': 1 })
  1317.  
  1318.  
  1319. def warning(msg, *args, **kwargs):
  1320.     """
  1321.     Log a message with severity 'WARNING' on the root logger.
  1322.     """
  1323.     if len(root.handlers) == 0:
  1324.         basicConfig()
  1325.     
  1326.     apply(root.warning, (msg,) + args, kwargs)
  1327.  
  1328. warn = warning
  1329.  
  1330. def info(msg, *args, **kwargs):
  1331.     """
  1332.     Log a message with severity 'INFO' on the root logger.
  1333.     """
  1334.     if len(root.handlers) == 0:
  1335.         basicConfig()
  1336.     
  1337.     apply(root.info, (msg,) + args, kwargs)
  1338.  
  1339.  
  1340. def debug(msg, *args, **kwargs):
  1341.     """
  1342.     Log a message with severity 'DEBUG' on the root logger.
  1343.     """
  1344.     if len(root.handlers) == 0:
  1345.         basicConfig()
  1346.     
  1347.     apply(root.debug, (msg,) + args, kwargs)
  1348.  
  1349.  
  1350. def log(level, msg, *args, **kwargs):
  1351.     """
  1352.     Log 'msg % args' with the integer severity 'level' on the root logger.
  1353.     """
  1354.     if len(root.handlers) == 0:
  1355.         basicConfig()
  1356.     
  1357.     apply(root.log, (level, msg) + args, kwargs)
  1358.  
  1359.  
  1360. def disable(level):
  1361.     """
  1362.     Disable all logging calls less severe than 'level'.
  1363.     """
  1364.     root.manager.disable = level
  1365.  
  1366.  
  1367. def shutdown():
  1368.     '''
  1369.     Perform any cleanup actions in the logging system (e.g. flushing
  1370.     buffers).
  1371.  
  1372.     Should be called at application exit.
  1373.     '''
  1374.     for h in _handlerList[:]:
  1375.         
  1376.         try:
  1377.             h.flush()
  1378.             h.close()
  1379.         continue
  1380.         if raiseExceptions:
  1381.             raise 
  1382.         
  1383.  
  1384.     
  1385.  
  1386.  
  1387. try:
  1388.     import atexit
  1389.     atexit.register(shutdown)
  1390. except ImportError:
  1391.     
  1392.     def exithook(status, old_exit = sys.exit):
  1393.         
  1394.         try:
  1395.             shutdown()
  1396.         finally:
  1397.             old_exit(status)
  1398.  
  1399.  
  1400.     sys.exit = exithook
  1401.  
  1402.